<?php

namespace App\Http\Controllers\Admin;

use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    private  function verfity(Request $request) {
        $this->validate($request, [
            'password'  => 'required|min:6',
        ]);
    }

    public function index()
    {
        return view('admin/user/index')->withUsers(User::all());
    }

    public function edit($id)
    {
        $user = User::find($id);
        if ($user) {
            return view('admin/user/edit')->withUser(User::find($id));
        } else {
            return "access denied";
        }
    }

    public function update(Request $request, $id)
    {
        $this->verfity($request);
        $exitUser = User::find($id);
        if (!$exitUser) {
            return redirect()->back()->withInput()->withErrors("用户不存在");
        }
        $getPassword = $request->get('password');
        if (password_verify($getPassword, $exitUser['password'])) {
            if ($request->get('name') && $request->get('email')) {
                $data['name'] = $request->get('name');
                $data['email'] = $request->get('email');
            }else if ($request->get('new_password1') && $request->get('new_password2')) {
                if ($request->get('new_password1') != $request->get('new_password2')) {
                    return redirect()->back()->withInput()->withErrors("两次输入密码不一样");
                }
                $data['password'] = bcrypt(trim($request->get('new_password1')));
            }else {
                return redirect()->back()->withInput()->withErrors("请输入修改数据");
            }
            $user = new User();
            if ($user->where('id', $id)->update($data)) {
                return redirect("admin/");
            } else {
                return redirect('admin/user/' . $id . '/edit')->withErrors("修改出错");
            }
        } else {
            return redirect('admin/user/' . $id . '/edit')->withErrors("密码错误");
        }
    }
}
